#include "SMemPatch.h"
#include "MsgWinApiLastError.h"

namespace TLib
{
	TRAINER_LIB_API SMemPatch::SMemPatch(unsigned int address, LPVOID newMem, unsigned int cBytes)
	{
		this->newMem   = newMem;
		this->address = address;
		this->cBytes  = cBytes;
		origMem = NULL;
	}
	TRAINER_LIB_API SMemPatch::~SMemPatch()
	{
		// Safe to delete null ptr
		delete [] origMem;
	}
	TRAINER_LIB_API void SMemPatch::Patch(HANDLE hProcess)
	{
		// Is the game patched yet?
		if (origMem == NULL)
		{
			// If not, read in the original ops so we can un-patch
			origMem = new BYTE[cBytes];
			if (!ReadProcessMemory(hProcess, (LPCVOID)address, origMem, cBytes, NULL))
				MsgWinApiLastError("ReadProcessMemory");
		}
		if (!WriteProcessMemory(hProcess, (LPVOID)address, newMem, cBytes, NULL))
			MsgWinApiLastError("WriteProcessMemory");
	}
	TRAINER_LIB_API void SMemPatch::UnPatch(HANDLE hProcess)
	{
		if (origMem == NULL)
			return ; // Hasn't been patched yet, no need to un-patch!
		if (!WriteProcessMemory(hProcess, (LPVOID)address, origMem, cBytes, NULL))
			MsgWinApiLastError("WriteProcessMemory");
	}

	TRAINER_LIB_API void SMemPatch::gameTurnedOff()
	{
		// Safe to delete null ptr
		delete [] origMem;
		origMem = NULL;
	}

}// Namespace TLib